# !/usr/bin/python3
# -*-coding:utf-8-*-
# Author: sanra
# CreatDate: 2020/11/18 11:15
# Description: 图片灰度处理
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np


def getimg():
    return Image.open("20190621162756153.jpg")


# 显示图片
def show_img(img, is_gray = False):
    if is_gray:
        plt.imshow(img, cmap = 'gray')
    else:
        plt.imshow(img)
    plt.axis("off")
    plt.show()


if __name__ == '__main__':
    # PIL自带的通用灰度计算
    # im = getimg()
    # im_gray = im.convert('L')
    # show_img(im_gray, True)

    # 自定义浮点灰度计算
    # [:, :, 0] 表示 取三维数组的第1维所有数据
    # im = getimg()
    # im = np.array(im)
    # im[:, :, 0] = im[:, :, 0] * 0.3
    # im[:, :, 1] = im[:, :, 1] * 0.59
    # im[:, :, 2] = im[:, :, 2] * 0.11
    # im = np.sum(im, axis = 2)
    # show_img(Image.fromarray(im), True)

    # # 自定义整数灰度计算，计算方法和浮点计算方法差不多
    # im1 = getimg()
    # # [..., 0] 表示三维数组的第1维数组全部
    # # 创建数组时指定数据类型，否则默认uint8乘法运算会溢出
    # im1 = np.array(im1, dtype = np.float32)
    # im1[..., 0] = im1[..., 0] * 30.0
    # im1[..., 1] = im1[..., 1] * 59.0
    # im1[..., 2] = im1[..., 2] * 11.0
    # im1 = np.sum(im1, axis = 2)
    # im1[..., :] = im1[..., :] / 100.0
    # show_img(Image.fromarray(im1), True)

    # # 平均值法
    # im2 = getimg()
    # im2 = np.array(im2, dtype = np.float32)
    # im2 = np.sum(im2, axis = 2)
    # im2[..., :] = im2[..., :] / 3.0  # 给数组所有值都除以3
    # show_img(Image.fromarray(im2), True)

    # # 移位法
    # im3 = getimg()
    # im3 = np.array(im3, dtype = np.int32)
    # im3[..., 0] = im3[..., 0] * 30.0
    # im3[..., 1] = im3[..., 1] * 151.0
    # im3[..., 2] = im3[..., 2] * 77.0
    # im3 = np.sum(im3, axis = 2)
    # arr = [np.right_shift(y.item(), 8) for x in im3 for y in x]
    # arr = np.array(arr)
    # arr.resize(im3.shape)
    # show_img(Image.fromarray(arr), True)

    # # 单通道法（只取绿色通道）
    # # 下面3个自由搭配，效果不一样
    # im4 = getimg()
    # im4 = np.array(im4, dtype = np.int32)
    # im4[..., 0] = 0
    # # im4[..., 1] = 0
    # im4[..., 2] = 0
    # im4 = np.sum(im4, axis = 2)
    # show_img(Image.fromarray(im4), True)

    # # 取中间阀值127，大于127的改成255，小于127的改成0
    # im5 = getimg()
    # im5 = np.array(im5.convert('L'))
    # im5 = np.where(im5[..., :] < 127, 0, 255)
    # show_img(Image.fromarray(im5), True)

    # # 取所有像素点灰度的平均值
    # # 计算所有像素点的平均值，然后以该值为界面二极化
    # im = getimg()
    # im_gray1 = im.convert('L')
    # im_gray1 = np.array(im_gray1)
    # avg_gray = np.average(im_gray1)
    # im_gray1 = np.where(im_gray1[..., :] < avg_gray, 0, 255)
    # show_img(Image.fromarray(im_gray1), True)

    # # 反相处理，
    # im = getimg()
    # im_gray = im.convert('L')
    # im_arr = np.array(im_gray)
    # im1 = 255 - im_arr
    # show_img(Image.fromarray(im1))

    im = getimg()
    im_gray = im.convert('L')
    im3 = 255.0 * (im_gray / 255.0) ** 2
    show_img(Image.fromarray(im3))
